package com.aj.activity;

import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.aj.activity.dialog.ProgressDialog;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.AccountDao;
import com.aj.databases.dao.FamilyDao;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.Account;
import com.aj.databases.entry.User;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.LoginRequest;
import com.aj.http.request.UploadJPushChannelRequest;
import com.aj.http.request.UserInfoRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.LoginRespons;
import com.aj.http.response.UserResponse;
import com.aj.utils.Contants;
import com.aj.utils.DesBase64Tool;
import com.easemob.EMCallBack;
import com.easemob.applib.controller.HXSDKHelper;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.DemoHXSDKHelper;
import com.umeng.analytics.MobclickAgent;

public class LoginActivity extends Activity {
	private static final String TAG = LoginActivity.class.getName();
	private EditText username;
	private EditText password;
	private Button login_button;
	private TextView forgetpassword;
	private TextView registeruser;
	public static LoginActivity instance;
	private FamilyDao familyDao;

	private ProgressDialog progressDialog;

	private void showProgressDailog() {
		if (progressDialog == null) {
			progressDialog = new ProgressDialog(this);
		}
		progressDialog.show();
		progressDialog.setContentText(getString(R.string.data_loading_text));
	}

	private void dimissProgressDailog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		// onresume时，取消notification显示
		HXSDKHelper.getInstance().getNotifier().reset();
		JPushInterface.onResume(this);
		// umeng
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		// umeng
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		JPushInterface.onPause(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initView();
	}

	private void initView() {
		instance = this;
		familyDao = new FamilyDao(this);
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		login_button = (Button) findViewById(R.id.login_button);
		forgetpassword = (TextView) findViewById(R.id.forgetpassword);
		registeruser = (TextView) findViewById(R.id.registeruser);
		ClickEvent clickEvent = new ClickEvent();
		login_button.setOnClickListener(clickEvent);
		forgetpassword.setOnClickListener(clickEvent);
		registeruser.setOnClickListener(clickEvent);
	}

	class ClickEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			Intent intent = null;
			switch (v.getId()) {
			case R.id.login_button:
				// TODO 登录
				showProgressDailog();
				LoginRequest loginRequest = new LoginRequest();
				familyDao.deleteAll();
				loginRequest.excute(LoginActivity.this, username.getText()
						.toString(), password.getText().toString(),
						new IHttpCallBack() {
							@Override
							public void success(String result) {
								try {
									LoginRespons loginRespons = new LoginRespons(
											new JSONObject(result));
									if (loginRespons
											.getCommon()
											.getReturnCode()
											.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
										final Account account = loginRespons
												.getAccount();
										LoveHomeApplication.token = account
												.getToken();
										UserInfoRequest userInfoRequest = new UserInfoRequest();
										userInfoRequest.excute(
												LoginActivity.this,
												account.getLast_used_user_id(),
												new IHttpCallBack() {
													@Override
													public void success(
															String result) {
														try {
															UserResponse userResponse = new UserResponse(
																	new JSONObject(
																			result));
															Common common = userResponse
																	.getCommon();
															if (common != null
																	&& common
																			.getResult() != null
																	&& common
																			.getReturnCode()
																			.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
																final User user = userResponse
																		.getUser();
																UserDao userDao = new UserDao(
																		LoginActivity.this);
																userDao.insertUser(user);
																AccountDao dao = new AccountDao(
																		LoginActivity.this);
																account.setLast_used_user_id(user
																		.getUser_id());
																account.setPassword(password
																		.getText()
																		.toString()
																		.trim());
																account.setPhone(username
																		.getText()
																		.toString()
																		.trim());
																account.setLastlogin_time(new Date());
																dao.insert(account);
																Toast.makeText(
																		LoginActivity.this,
																		getString(R.string.login_success_text),
																		Toast.LENGTH_LONG)
																		.show();
																dimissProgressDailog();
																// 上传JPush别名
																// 成功
																new UploadJPushChannelRequest()
																		.excute(LoginActivity.this,
																				user.getUser_id(),
																				JPushInterface
																						.getRegistrationID(LoveHomeApplication.application),
																				new IHttpCallBack() {
																					@Override
																					public void success(
																							String result) {

																						Log.e(TAG,
																								"result:"
																										+ result);
																					}

																					@Override
																					public void fail(
																							String result) {
																						Log.e(TAG,
																								"result:"
																										+ result);

																					}
																				});

																// 登录环信
																if (!DemoHXSDKHelper
																		.getInstance()
																		.isLogined()) {
																	String userName = user
																			.getUser_id();
																	String password = DesBase64Tool
																			.encryptDES("aj2015");
																	EMChatManager
																			.getInstance()
																			.login(userName,
																					password,
																					new EMCallBack() {

																						@Override
																						public void onSuccess() {
																							// 登陆成功，保存用户名密码
																							LoveHomeApplication.application
																									.setUserName(account
																											.getLast_used_user_id());
																							LoveHomeApplication.application
																									.setPassword(account
																											.getPassword());

																							try {
																								// **
																								// 第一次登录或者之前logout后再登录，加载所有本地群和回话
																								// **
																								// manually
																								// load
																								// all
																								// local
																								// groups
																								// and
																								EMGroupManager
																										.getInstance()
																										.loadAllGroups();
																								EMChatManager
																										.getInstance()
																										.loadAllConversations();
																								// 处理好友和群组
																								// initializeContacts();
																							} catch (Exception e) {
																								e.printStackTrace();
																								// 取好友或者群聊失败，不让进入主页面
																								runOnUiThread(new Runnable() {
																									@Override
																									public void run() {
																										DemoHXSDKHelper
																												.getInstance()
																												.logout(true,
																														null);
																										Toast.makeText(
																												getApplicationContext(),
																												R.string.login_failure_failed,
																												1)
																												.show();
																									}
																								});
																								return;
																							}
																							// 更新当前用户的nickname
																							// 此方法的作用是在ios离线推送时能够显示用户nick
																							boolean updatenick = EMChatManager
																									.getInstance()
																									.updateCurrentUserNick(
																											LoveHomeApplication.currentUserNick
																													.trim());
																							if (!updatenick) {
																								Log.e("LoginActivity",
																										"update current user nick fail");
																							}
																							// //
																							// 进入主页面
																							// Intent
																							// intent
																							// =
																							// new
																							// Intent(
																							// LoginActivity.this,
																							// MainActivity.class);
																							// startActivity(intent);
																							//
																							// finish();
																						}

																						@Override
																						public void onProgress(
																								int progress,
																								String status) {
																						}

																						@Override
																						public void onError(
																								final int code,
																								final String message) {
																							// if
																							// (!progressShow)
																							// {
																							// return;
																							// }
																							runOnUiThread(new Runnable() {
																								@Override
																								public void run() {
																									// pd.dismiss();
																									Toast.makeText(
																											getApplicationContext(),
																											getString(R.string.Login_failed)
																													+ message,
																											Toast.LENGTH_SHORT)
																											.show();
																								}
																							});
																						}
																					});
																}
																finish();
															} else {
																Toast.makeText(
																		LoginActivity.this,
																		common.getErrorMsg(),
																		Toast.LENGTH_LONG)
																		.show();
															}
														} catch (JSONException e) {
															e.printStackTrace();
														}
													}

													@Override
													public void fail(
															String result) {
														try {
															UserResponse userResponse = new UserResponse(
																	new JSONObject(
																			result));
															Toast.makeText(
																	LoginActivity.this,
																	userResponse
																			.getCommon()
																			.getErrorMsg(),
																	Toast.LENGTH_LONG)
																	.show();
														} catch (JSONException e) {
															e.printStackTrace();
														}
														dimissProgressDailog();
													}
												});
									} else {
										Toast.makeText(
												LoginActivity.this,
												loginRespons.getCommon()
														.getErrorMsg(),
												Toast.LENGTH_LONG).show();
										dimissProgressDailog();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}

							}

							@Override
							public void fail(String result) {
								try {
									LoginRespons loginRespons = new LoginRespons(
											new JSONObject(result));
									Toast.makeText(
											LoginActivity.this,
											loginRespons.getCommon()
													.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
								dimissProgressDailog();
							}
						});
				break;
			case R.id.forgetpassword:
				Toast.makeText(LoginActivity.this, "忘记秘密", Toast.LENGTH_LONG)
						.show();
				intent = new Intent(Contants.ENTER_PHONE_ACTION);
				intent.putExtra(Contants.PAGEFLAG_STRING,
						Contants.FORGET_PAGEFLAG_STRING);
				startActivity(intent);
				break;
			case R.id.registeruser:
				Toast.makeText(LoginActivity.this, "注册", Toast.LENGTH_LONG)
						.show();
				intent = new Intent(Contants.ENTER_PHONE_ACTION);
				intent.putExtra(Contants.PAGEFLAG_STRING,
						Contants.REGISTER_PAGEFLAG_STRING);
				startActivity(intent);
				break;
			default:
				break;
			}
		}
	}
}
